import { defineStore } from 'pinia'
import { ref } from 'vue'
import { menuData } from './menuData.ts'
import { toTree } from '@/utils/ArrayToTree'
import { useRouter } from 'vue-router'
import { staticRoute } from '@/router/staticRoute.ts'

export const menuStore = defineStore('menu', () => {
  // 接口返回菜单list
  const menuList = ref([] as any)
  // list格式化后的菜单树
  const menuMap = ref({} as any)
  const router = useRouter()
  // 菜单对应的层级关系快速查询
  const menuLevelList = ref({})
  const dynamicRoute = ref([] as any)
  // 分离式菜单展开项
  const subMenu = ref([])
  const sideDrawerMenu = ref(false)

  // 分离式菜单一级菜单选择项
  const firstActiveMenu = ref('')
  const firstActiveMenuName = ref('')

  // todo zpd for real this data need fetch from backend
  function initMenu()  {
    menuList.value = menuData.menuList
    menuMap.value = toTree(menuData.menuList)
    // 初始化菜单树层级关系
    makeMenuMapLevelList(menuMap.value)
    dynamicRoute.value = initRoute(menuList.value)
    staticRoute[0].children = (staticRoute[0].children as any).concat(dynamicRoute.value)
    router.addRoute(staticRoute[0])
  }

  /**
   * 初始化菜单树层级关系，递归生成层级数组
   * @param menuMap
   * @param levelList
   */
  const makeMenuMapLevelList = (menuMap: any, levelList: any[] = []) => {
    for (const key in menuMap) {
      const item = menuMap[key]
      const list = [...levelList]
      list.push(item.id)
      menuLevelList.value[item.id] = list
      if (item.children) {
        makeMenuMapLevelList(item.children, list)
      }
    }
  }

  const initRoute = (menuList: any) => {
    const menus = [] as any[];
    menuList.forEach((item) => {
      if (item.path && /\S/.test(item.path)) {
        const route = {
          name: item.perms,
          path: item.path,
          component: null as any,
          meta: {
            id: item.id,
            title: item.name,
          }
        }
        try {
          route.component = () => import(`@/views${item.path}/index.vue`)
        } catch (e) {
          console.error(e)
        }
        menus.push(route)
      }
    })
    return menus
  }

  return { menuList, menuMap, initMenu, firstActiveMenu, menuLevelList, dynamicRoute, subMenu, firstActiveMenuName, sideDrawerMenu }
})
